const query = require('../config/sql');
const _ = require('lodash');
module.exports = async function getCommentTree(comments) {
    // 创建一个新的数组来存储带有回复的评论  
    const commentTree = [...comments];

    // 创建一个Promise数组来保存所有的查询  
    const promises = comments.map(async ele => {
        // 使用参数化查询来避免SQL注入  
        const sql = `SELECT c.comment_id, c.content,c.parent_comment_id, c.timestamp, c.like_count , c.reply_count,
                      u.nickname , u.avatar, c.user_id
                      FROM commentinfo c    
                      JOIN users u ON c.user_id = u.user_id    
                      WHERE c.parent_comment_id = ?`;

        // 执行查询并获取结果  
        const res = await query(sql, [ele.comment_id]);

        // 将回复添加到当前评论的reply属性中  
        ele.reply = res;

        // 如果存在回复，递归地构建它们的树  
        if (res.length !== 0) {
            ele.reply = await getCommentTree(res);
        }
    });

    // 等待所有查询完成  
    await Promise.all(promises);
    // 返回带有回复的评论树  
    return flattenComments(commentTree);
};

function flattenComments(comments) {  
    const flattened = [];  
  
    // 遍历所有一级评论  
    for (const comment of comments) {  
        const currentReply = [];  
  
        // 如果当前评论有reply，则递归处理这些reply  
        if (comment.reply) {  
            for (const reply of comment.reply) {  
                const flattenedReply = flattenDeepReplies(reply, comment.nickname);  
                currentReply.push(...flattenedReply);  
            }  
        }  
  
        // 更新当前一级评论的reply数组  
        comment.reply = currentReply;  
  
        // 将处理过的一级评论添加到结果数组中  
        flattened.push(comment);  
    }  
  
    return flattened;  
}  
  
// 递归扁平化三级及以下的评论  
function flattenDeepReplies(reply, parentNickname) {  
    const flattened = [];  
  
    // 如果当前评论还有reply，递归处理  
    if (reply.reply) {  
        for (const deepReply of reply.reply) {  
            // 给当前评论添加to_name字段  
            deepReply.to_name = parentNickname;  
  
            // 递归处理更深层的回复  
            const flattenedDeepReply = flattenDeepReplies(deepReply, deepReply.comment_id);  
            flattened.push(...flattenedDeepReply);  
        }  
  
        // 去除当前评论的reply字段，因为我们已经将其扁平化了  
        delete reply.reply;  
    }  
  
    // 将当前评论（二级评论）添加到结果数组中，不添加to_id  
    flattened.push(reply);  
  
    return flattened;  
}  

